//var createError = require('http-errors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var express = require('express');
var app = express();
app.use(express.json()) //识别客户端传递过来的json
app.use(require('cors')()) //允许跨域
const jwt = require('jsonwebtoken')//生成token
const SECRET="huidbgirbrvigbiv"

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

const {User} = require('./db/db.js')
console.log(User);

//获取用户数据
app.get('/api/user',async(req,res)=>{
  const user = await User.find()
  res.send(user)
})
//创建用户
app.post('/api/register',async(req,res)=>{
  const users = await User.create({
    username:req.body.username,
    password:req.body.password
  })
  //console.log(req.body);
  res.send(users)
})
//登录验证
app.post('/api/login',async(req,res)=>{
  const user = await User.findOne({
    username:req.body.username
  })
  if (!user) {
    return res.status(422).send({
      message:"用户名不存在"
    })
  }
  //compareSync
  const isPasswordValid=require('bcryptjs').compareSync(
    req.body.password,
    user.password
  )
  if (!isPasswordValid) {
    return res.status(422).send({
      message:"密码无效"
    })
  }
  //生产token
  const token = jwt.sign({
    id:String(user._id)
  }, SECRET)
  res.send({
    user,
    token:token
  })
})
//profile个人信息验证
/* app.get('/api/profile',async(req,res)=>{
  const raw = String(req.headers.authorization).split(' ').pop();
  //const tokenData = jwt.verify(raw, SECRET)
  const {id} = jwt.verify(raw, SECRET)
  console.log(id);
  
  const user=await User.findById(id)
  res.send(user)
})
 */
//采用中间件写法
const auth = async(req,res,next)=>{
  const raw = String(req.headers.authorization).split(' ').pop()
  const {id} = jwt.verify(raw, SECRET)
  req.user = await User.findById(id)
  next()
}
app.get('/api/profile',auth,async(req,res)=>{
  res.send(req.user)
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
/* app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
  next()
});
 */
app.listen(3009, () => {
  console.log('http://localhost:3009');

});
